package model;

import java.security.MessageDigest;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.codec.binary.Hex;

import web.model.Bean;

/**
 * User bean
 * 
 * @author orlin
 */
public class UserBean extends Bean {

	public static final DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");

	private String username = null;
	private String password = null;
	private String email = null;
	private UserMode mode = null;
	private Date birth = null;

	public UserBean() {
		super();
	}

	public UserBean(String username, String password, String email, UserMode mode, Date birth) {
		super();
		this.username = username;
		this.password = shaPassword(password);
		this.email = email;
		this.mode = mode;
		this.birth = birth;
	}

	public static Date a2d(String a) {
		try {
			return formatter.parse(a);  
		} catch (ParseException e) {
			return null;
		}
	}

	private String shaPassword(String password) {
		try {
			MessageDigest cript = MessageDigest.getInstance("SHA-1");
			cript.reset();
			cript.update(password.getBytes("UTF-8"));
			String shaPassword = Hex.encodeHexString(cript.digest()).toUpperCase();
			return shaPassword;
		} catch (Exception e) {
			throw new Error("User Password Failed: this should never happen: " + e.getMessage());
		}
	}

	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public UserMode getMode() {
		return mode;
	}
	public void setMode(UserMode mode) {
		this.mode = mode;
	}
	public void setMode(String mode) {
		this.mode = UserMode.valueOf(mode);
	}
	public Date getBirth() {
		return birth;
	}
	public String getBirthAsStr() {
		return birth != null ? formatter.format(birth) : "";
	}
	public void setBirth(Date birth) {
		this.birth = birth;
	}
	public void setBirth(String birth) {
		this.birth = a2d(birth);
	}

	public boolean checkPass(String password) {
		return this.password.equals(shaPassword(password));
	}

	@Override
	public String toString() {
		StringBuffer line = new StringBuffer();
		line.append("UserBean [id:");
		line.append(getId());
		line.append(", username:");
		line.append(username);
		line.append(", password:");
		line.append(password);
		line.append(", email:");
		line.append(email);
		line.append(", mode:");
		line.append(mode);
		line.append(", birth:");
		line.append(getBirthAsStr());
		line.append("]");
		return line.toString();
	}
}
